package com.fudan.cfg.base;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;

import com.fasterxml.jackson.annotation.JsonFormat.Feature;
import com.fudan.cfg.dataset.ElasticsearchDataset;
import com.fudan.cfg.dataset.HDFSDataset;
import com.fudan.cfg.dataset.MysqlDataset;
import com.fudan.cfg.dataset.MysqlFDataset;
import com.fudan.cfg.dataset.OracleDataset;
import com.fudan.run.ctx.DatasetContext;
import com.fudan.run.dataset.DatasetHandler;

public abstract class DatasetDef extends TypeNode{

	public DatasetDef(String name,String type) {
		super(name,type);
	}


	public static DatasetDef buildFromConfiguration(Map<String,Object> configuration,DatasetContext datasetContext) {
		String name = (String) configuration.get(NAME_TAG);
		String type = (String) configuration.get(TYPE_TAG);
		Class<? extends DatasetDef> nodeClass = datasetContext.getParser(type);
		if(nodeClass != null) {
			try {
				return nodeClass.getConstructor(String.class,String.class).newInstance(name,type).build(configuration);
			} catch (InstantiationException | IllegalAccessException | IllegalArgumentException
					| InvocationTargetException | NoSuchMethodException | SecurityException e) {
				throw new RuntimeException(String.format("dataset配置解析器构建失败，type: %s",type),e);
			}
		}
		throw new RuntimeException(String.format("dataset没有匹配的配置解析器，type: %s",type));
	}

	public abstract DatasetDef build(Map<String,Object> configuration);

	@Override
	public String toString() {
		ObjectMapper om = new ObjectMapper();
		try {
			return om.writerWithDefaultPrettyPrinter().writeValueAsString(this);
		} catch (IOException e) {
			return super.toString();
		}
	}
}
